package com.zb.app.service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zb.app.mapper.ApUserMapper;
import com.zb.app.mapper.ApUserRealnameMapper;
import com.zb.app.service.ApUserRealnameService;
import com.zb.common.exception.CommonException;
import com.zb.feigns.ArticleFeign;
import com.zb.feigns.WemediaFeign;
import com.zb.model.common.PageResult;
import com.zb.model.common.Result;
import com.zb.model.dto.user.AuthDTO;
import com.zb.model.pojo.article.ApAuthor;
import com.zb.model.pojo.user.ApUser;
import com.zb.model.pojo.user.ApUserRealname;
import com.zb.model.pojo.wemedia.WmUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl implements ApUserRealnameService {

    @Autowired
    private ApUserRealnameMapper realnameMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    @Override
    public PageResult pageList(AuthDTO dto) {
        Integer page = dto.getPage();
        Integer pageSize = dto.getPageSize();
        PageHelper.startPage(page, pageSize);
        Page<ApUserRealname> data = realnameMapper.pageList(dto);
        return PageResult.builder().total(data.getTotal()).rows(data.getResult()).build();
    }

    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 1000000)
    @Override
    public Result updateStatusById(AuthDTO dto, Short status) {
        //2 查询当前认证用户是否在
        ApUserRealname apUserRealname = realnameMapper.findById(dto.getId());
        if (apUserRealname == null) {
            throw new CommonException(201, "待审核 实名认证信息不存在");
        }

        if (!apUserRealname.getStatus().equals(Short.valueOf("1"))) {
            throw new CommonException(201, "实名认证信息非待审核状态");
        }

        ApUser apUser = apUserMapper.selectByUserId(apUserRealname.getUserId());
        if(apUser == null){
            throw new CommonException(201, "实名认证信息 关联 app的用户不存在");
        }
        //3 更新认证用户信息
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        realnameMapper.update(apUserRealname);

        //4 认证状态如果为 通过
        if (Short.valueOf("9").equals(status)) {
            //4.1 创建自媒体账户
            Integer wmUserId = createWmUser(dto, apUser);
            //4.2 创建作者信息
            createApAuthor(apUser, wmUserId);
        }
        //5 返回结果
        return Result.SUCCESS();
    }

    @Override
    public ApUserRealname getById(Integer id) {
        return realnameMapper.getById(id);
    }

    /**
     * 4.2 创建作者信息
     * @return
     */
    private void createApAuthor(ApUser apUser, Integer wmUserId) {
        //1 检查是否成功调用
        Result<ApAuthor> apAuthorResult = articleFeign.findByUserId(apUser.getId());
        if(apAuthorResult.getCode().intValue() != 200){
            throw new CommonException(201, "查询作者失败");
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = (ApAuthor) apAuthorResult.getData();
        if (apAuthor != null) {
            throw new CommonException(201, "作者信息已存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(apUser.getName());
        apAuthor.setType(0); // 自媒体人类型
        apAuthor.setUserId(apUser.getId()); // APP 用户ID
        apAuthor.setWmUserId(wmUserId); // 自媒体用户ID
        Result result = articleFeign.save(apAuthor);
        //4. 结果失败，抛出异常
        if (result.getCode() != 200) {
            throw new CommonException(201, "新增作者失败");
        }
    }
    /**
     * 4.1 创建自媒体账户
     * @param apUser  APP端用户
     */
    private Integer createWmUser(AuthDTO dto, ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        Result<WmUser> res = wemediaFeign.findByName(apUser.getName());
        String wmUserResultString = JSONObject.toJSONString(res.getData());
        WmUser wmUser = JSONObject.parseObject(wmUserResultString,WmUser.class);
        if(res.getCode().intValue() != 200){
            throw new CommonException(201, res.getMessage());
        }
        if (wmUser != null) {
            throw new CommonException(201, "自媒体用户信息已存在");
        }
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(Short.valueOf("9"));

        Result<Integer> res1 = wemediaFeign.save(wmUser);
        if(res.getCode() != 200){
            throw new CommonException(201, "新增自媒体用户失败");
        }
        return JSONObject.parseObject(JSONObject.toJSONString(res1.getData()),Integer.class);
    }
}
